package com.qigao.mall.channel.weichat;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AesGcmExample2 {
    private static final String ALGORITHM = "AES/GCM/NoPadding";
    private static final int TAG_LENGTH_BIT = 128;
    private static final int NONCE_LENGTH_BYTE = 12;
    private static final String AES_KEY = "3386ead9287e2f9e78B507F7C0D4D281"; // APIv3密钥
    private static final String TRANSFORMATION_PKCS1Padding = "RSA/ECB/PKCS1Padding";
    private static String aesgcmDecrypt(String aad, String iv, String cipherText) throws Exception {
        final Cipher cipher = Cipher.getInstance(ALGORITHM, "SunJCE");
        SecretKeySpec key = new SecretKeySpec(AES_KEY.getBytes(), "AES");
        GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, key, spec);
        cipher.updateAAD(aad.getBytes());
        return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText)));
    }
    public static void main(String[] args) {
        final String associatedData = "certificate"; // encrypt_certificate.associated_data
        final String nonce = "11b957728a8b"; // encrypt_certificate.nonce
        final String cipherText = "Xt4VCiZGlHp0qC8S09iWwTfti7qp5cmZF/QaApYZVvJk82+2tlImUwuswHLFU6NFpTFWGQJZ+as7S6Vsez1rpSGDZeVPR1ttOWJ+oklyQHx4FHekEnlP0pfvCfWkcRHKPFQqG/WHE+DBLwHDdL1E77VqXgKHNsVZFfNAaC7+XmWWExDXI0v+QDCXXj+UFdgln59mPCi2F2lPyWCOqM4yVtrPxnz/DWEHybkJKRPSZ3d5fC+SsOxrI0eqiXvP/pBxK0Vrn82v4jSLl9hczxmH4u32+u1nFxaBa/yy6jsOXI5JVrj9XcnxAKSoi6t9j4sh5275Mtr2VJKJSBkblfVBFpm0as542Vd/pCf75KIiiRzdMO36HnlzILA7ChWbbg5eypp9fDzsvuzDDRd7O9mduyKPKBPkuluasn7qsfwzFcd4HRLkoD3SccG3E6mTctYXWDUQulVfc5wjF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kjcB6YcSJTktdOtIO28pq8lVEsAeVzxKn8HpQtlHvi2+imXwq5/THOFmWn4GxRIfTXTZC7Qu4pXohmKx4Iu2sSAAivta71cmDuijRRd5xD4Gr9Kn28eM6+l6A9TrZjIbauexSLVQeMhdPUCrDb4vVgf8IfetuXXN3LXoiUGit8Ll16JsHUsSKY1O2va8/X3PmG32YsW1QTiN/b2yFYcvSjtiGbyYPfSfsY/OoP3Wwzwe7lCLvmSTkXRf+l42fkza87VceHSBbybin7KfMGppiDcOd6ZYoBXIyfnbqIXH3H59bTX6416hZtbhIZdQmXrtzujUHt7m3M8g=="; // encrypt_certificate.ciphertext
        try {
            String wechatpayCert = aesgcmDecrypt(associatedData, nonce, cipherText);
            System.out.print(wechatpayCert);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
